/** -----------------------------------Ccay.Personalized------------------------- */

Ccay.Personalized = {
	_settings : new Ccay.HashMap(),
	
	_saveKeys : {}, //缓存需要延时保存的key数组
	/**
	 * 全局设置信息，默认
	 * 
	 * @type {object}
	 */
	global :{
		common : {
			wideScreen : ( workspaceVO.config.IsWideScreen == true ) ? 1 : 0,
			lang:workspaceVO.currentLanguage,
			grid:{
				pageSize:Ccay.UI.Config.pager.defaultSize
			},
			lastCheckBrowserDate:0,
			pushMsg:{
				enable:1,
				items:null
			},
			infoTipLanguage:workspaceVO.currentLanguage,
			timeZone:"076+8"
		}
	},

	/**
	 * 获取当前页面的用户个性化设置key
	 * 
	 * @return {string} key
	 */
	getPageKey : function() {
		var keys = window.location.href.split("#!");
		if (keys.length > 1) {
			return keys[1].split("?")[0];
		} else {
			return false;
		}
	},
	
	getKeyById : function(id){
		var pageKey = this.getPageKey();
		return pageKey ? pageKey + "#" + id : false;
	},
	/**
	 * 得到当前页面的个性化设置信息
	 * 
	 * @return {}
	 */
	getCurrPageSettings : function(itemId) {
		var key = this.getPageKey(), setting = null;
		if(!key){
			return 	null;
		}
		if(itemId){
			setting =  this._settings.get(key + "#" + itemId);
			if(!setting){
				setting = this._settings.get(key);
				if(setting &&  setting.grid && setting.grid[itemId]){
					setting = setting.grid[itemId];
				}else if( setting && setting[itemId]){
				    setting = setting[itemId]
				}
			}
		}else{
			setting = this._settings.get(key);
		}
		return setting;
	},
	/**
	 * 应用用户全局设置
	 */
	init : function() {
		var theme = Ccay.Personalized.global.common.theme; //提升性能,防止在重新加载页面时菜单构建方法执行多次,如果theme为undefined即页面重新加载
		if(Ccay.Config.Personalized.open){
			this.global = $.extend(true,this.global,this._settings.get("global"));
			//解决chrome浏览器普宽屏切换时出现变形 add by twx305111 2015.8.21
			$('#bodyfixed #leftMenuContent').css('position','relative');
			if (this.global.common.wideScreen ) {
				 $(document.body).addClass('fullScreen');
				 setTimeout(function(){
					 $("#fullScreen_a").text($i18n("ccay.home.label.screen"));
					 $('#W3AppTop_Header').width("98%");
				 } ,0);
			}else{
				$("#fullScreen_a").text($i18n("ccay.home.label.fullscreen"));
				$('#W3AppTop_Header').width("980px");
			 	$(document.body).removeClass("fullScreen");
			}
			// 执行所有的resize
			Ccay.UI.Resizes.fire("toggleScreen");
			$('#bodyfixed #leftMenuContent').css('position','fixed');
			
			theme && Ccay.UI.TopMenu && Ccay.UI.TopMenu.helper.buildTopMenu();  //菜单置顶,重新构建菜单
			theme && Ccay.UI.TopItem && Ccay.UI.TopItem.helper.buildTopItem();  //菜单置顶 (支持三级),重新构建菜单
			if (this.global.common.grid.pageSize) {
				Ccay.UI.Config.pager.defaultSize = this.global.common.grid.pageSize
			}
			
		}else{
			Ccay.Personalized=null;
		}
		
	},

	/**
	 * 得到worskpaceVO中的用户喜好数据，并且生成Map形式保存在个性化模块js对象中
	 */
	load : function() {
		
		var list = workspaceVO.userSettingList || [];
		
		for (var i = 0; i < list.length; i++) {
			var item = list[i];
			try {
				item.settingContent = JSON.parse(item.settingContent)
				item.settingContent._settingId = item.settingId;
			} catch (e) {
			};
			this._settings.put(item.settingKey, item.settingContent);
		}
		
		// 清空原有数据对象
		workspaceVO.userSettingList = null;

	},
	
	
	/**个性化更新方法
	 * @param {string} controlId 组件id
	 * @param {object} settingContent 项具体设置
	 * @param {fn} callback  保存回调，有回调的保存将会立即执行
	 * @param {fn} displace  是否替换，替换则不与原有设置进行合并
	 */
	saveSetting : function(controlId, newSettings,callback,displace){
		
		var key = this.getKeyById(controlId), settings = this._settings.get(key) || {};
		if(!key){
			return;//如果没有获取到key，则不保存；
		}
		var profile = $("#profileText"),profilekey=null;
		profile.length && (profilekey=profile.val().trim()+"!"+key);
		//将新设置的项，进行计算合并，并保存到全局个性化缓存 settings中
		settings = displace ? newSettings : $.extend(settings, newSettings);
		this._settings.put(key,settings);
		
		if(typeof callback == "function"){
			this.saveItem({settingKey : key, settingContent : JSON.stringify(settings)}, callback);
			profilekey&&this.saveItem({settingKey : profilekey, settingContent : JSON.stringify(settings)}, callback);
		}else{
			//将key值添加到 延时保存key数组中，等待;
			this._saveKeys[key] = true;
			setTimeout(function(){
				var saveKeys = Ccay.Personalized._saveKeys; 
				Ccay.Personalized._saveKeys = {};
				for(var k in saveKeys){
					var setting = Ccay.Personalized._settings.get(k);
					if(!$.isEmptyObject(setting)){
						Ccay.Personalized.saveItem({settingKey : k, settingContent :  JSON.stringify(setting)}, null, false);
					}
				}
			},Ccay.Config.Personalized.delay);
		}
	},

	/**
	 * 保存方法
	 * @param {object} content
	 * @param {bool} isGlobal 是否是报错全局设置
	 * @param {fn} callback  保存回调，有回调的保存将会立即执行
	 */
	save : function(content, isGlobal,callback,autoLoading) {
		//根据参数到得到key， 并根据key拿到 设置项 （key值两种 一种全局global 另一种为当前页面url）
		var key = isGlobal ? "global" :  content && content.historyKey || this.getPageKey(), item = this._settings.get(key);
		
		//如果通过key没有获取到个性化配置值，则根据key类型拿到默认设置对象
		if(!item){
			item = isGlobal ?  this.global : {};
		}
		
		if(!key){
			return; //如果没有获取到key，则不保存；
		}

		// 以保存的theme为主，为空时不保存此项
		if(isGlobal && !content.common.theme){
			delete item.common.theme;
		}
		//将新设置的项，进行计算合并，并保存到全局个性化缓存 settings中
		if($.isArray(content)){
			this._settings.put(key,content);
		}else{
			item = $.extend(true, item, content);
			this._settings.put(key,item);
		}
		if(typeof callback == "function"){
			this.saveItem({settingKey : key, settingContent : JSON.stringify(item)}, callback, autoLoading)
		}else{
			//将key值添加到 延时保存key数组中，等待;
			this._saveKeys[key] = true;
			setTimeout(function(){
				var saveKeys = Ccay.Personalized._saveKeys; 
				 Ccay.Personalized._saveKeys = {};
				for(var skey in saveKeys){
					var sitem = Ccay.Personalized._settings.get(skey);
					Ccay.Personalized.saveItem({settingKey : skey, settingContent :  JSON.stringify(sitem)}, null, false);
				}
			},Ccay.Config.Personalized.delay);
		}
		
	},
	
	saveItem : function(setting, callback, autoLoading){
		if(setting.settingContent.length<4000){
			Ccay.doPost("services/ccay/personalized/setting/createSingle",setting, callback || $.noop,null,"",autoLoading);
		}
	},
	
	deleteSetting : function(itemId){
		var sets = this.getCurrPageSettings(), newSets = this.getCurrPageSettings(itemId);
		if(sets && sets[itemId] && sets._settingId){
			delete sets[itemId];
			Ccay.doDelete("services/ccay/personalized/setting/delSingle/"+ sets._settingId,null, $.noop,null,"",false);
		}
		if(newSets){ 
			if( newSets._settingId){
				Ccay.doDelete("services/ccay/personalized/setting/delSingle/"+newSets._settingId,null, $.noop,null,"",true);
			}else{
				this.saveItem({settingKey: this.getKeyById(itemId),settingContent :"{}"}, $.noop,null,"",true);
			}
			this._settings.put(this.getKeyById(itemId),{});
		}
	},
	
	/**
	 * 处理grid的个性化显示
	 * 
	 * @param {}
	 *            options
	 */
	gridProcessor : function(options) {
		//如果grid个性化开关打开，就应用用户的个性化信息

		var columns = options.columns || [], gridId = options.id;
		var setting = this.getCurrPageSettings(gridId) ;
		if(!setting){
			return;
		}
		
		var shows = setting.show,widths = setting.widths;
		$.each(columns, function(index, column) {
			//个性化 显示隐藏列设置
			if(shows && column.hideable!==false){ 
				if(shows[column.id]){
					column.hidden = false;
				}else{
					column.hidden = true;
				}
			}
			//根据个性化 设置列宽度
			if(widths && column.resizable!==false){ 
				if(widths[column.id]){
					column.width = widths[column.id];
				}
			}
		});
	},
	/** 处理iGrid的个性化显示
	 *  @param {} grid
	 *  @param {} op
	 */
	iGridProcessor: function (grid, op) {
		var setting = this.getCurrPageSettings(grid.id), isChange;
		// 判断是否有必填项隐藏，若有显示该列
		if (!op._reIniting && setting) {
			// 判断个性化设置是否存在兼容性问题，如果存在，删除该个性化设置并且个性化不生效。
			if(setting.sort!==undefined && typeof setting.sort!="string"){
				this.deleteSetting(grid.id);
				return;
			}
			// 将原始op替换成改变后的op
			Ccay.DataHelper.applyChangeData(op, setting, {columns: "field"}, function(key, changeData, changeIdx, oldData, oldIdx) {
				// 对于列参数进行判断
				if (key == "field") {
					// 原始数据是必填项，并且又是隐藏的，则修改隐藏参数
					if (oldData) {
						if (oldData.rule && oldData.rule.required && changeData.hidden) {
							isChange = true;
							changeData.hidden = false;
						}
					} else {
						// 新增数据存在，而原始数据不存在，则将新增数据删除
						isChange = true;
						setting.columns.splice(changeIdx, 1);
						return false;
					}
				}
			});
			grid.setSortSetting();
			if(op.colsort !== false){
				//修正colsort 顺序 
				grid.colsort(); 
			}
			// 个性化数据是否存在变更，存在，则进行保存
			isChange && Ccay.Personalized.saveSetting(grid.id, setting);
		}
	},
	/** 处理表格字段的显示隐藏
	 *  @param {} widget
	 *  @param {} op
	 */
	widgetProcessor: function (widget, op) {
		var setting = this.getCurrPageSettings(widget.id);
		// 判断是否有必填项隐藏，若有显示该列
		if (setting) {
			op._customSettings = setting;
		}
	}

};
Ccay.Personalized.load();
//封装localStorage接口
Ccay.LocalStorage = {
	getItem : function(key){
		if(localStorage){
			return localStorage.getItem("{0}_{1}_{2}".formatText(workspaceVO.user.userId, workspaceVO.config.appName, key));
		}
	},
	
	setItem : function(key,value){
		if(localStorage){
			try{
				localStorage.setItem("{0}_{1}_{2}".formatText(workspaceVO.user.userId, workspaceVO.config.appName, key), value);
			}catch(e){
				Ccay.Log.info("localStorage超出存储，清理掉比较老的5条数据")
				this.delOldPartItems(10)

			}
		}
	},
	delOldPartItems : function(delCount){
		var list=[];
		for(var attr in localStorage){
			var value = localStorage[attr], regExp = /"creationDate":(\d+)/;
			if( regExp.test(value)){
				list.push({key : attr, creationDate :regExp.exec(value)[1] * 1})
			}
		}
		Ccay.DataHelper.sort("creationDate", "asc", list );
		for(var i=0;i < delCount ; i++ ){
			if(list[i]){
				localStorage.removeItem(list[i].key)
			}
		}
	}
}

Ccay.History ={
	config:{storage : 0, length : 10, enable : 0},
	init : function(){
		try{
			if(typeof workspaceVO.config.historySettings =="string"){
				var sets = workspaceVO.config.historySettings = Ccay.DataHelper.toJson(workspaceVO.config.historySettings);
				 $.extend(this.config,sets);
			}
		}catch(e){
			Ccay.Log.error("数据字典历史记录配置出错")
		}
	},
	saveList :function(key, datas, valueField){
		if(datas.length > 10){
			datas = datas.slice(0, 10);
		}
		for(var i=0, data; data = datas[i]; i++){
			this.save(key, data[valueField], null, this.getHistory(key, true));
		}
	},
	/**根据配置保存历史选择记录（个性化与localStorage）
	 * @param key    保存的key
	 * @param value  保存的值
	 * */
	save : function(key,value,data, historys){
		if(!key || (!value && value !== 0)){
			return;
		}
		var  findEquals = false, historyList = historys || this.getHistory(key) ;
		//遍历原有的历史记录，如果能找到与当前value对应的值，则更新对应项的选择次数与最近使用时间
		for(var i = 0,item; item = historyList[i]; i++){
			if(item.value == value){
				item.times ++;
				item.time = new Date().getTime();
				if(data){
					item.data = data;
				}
				findEquals = true;
			}
		}
		if(!findEquals){
			//如果保存的长度大于设置的限制，则需要删掉多余的配置
			while(historyList.length && historyList.length >= this.config.length){ 
				historyList.pop();
			}
			//data  值 (times 次数) (time 最近使用时间)
			historyList = [{value : value, times : 1, time : new Date().getTime(), data : data}].concat(historyList)
		}
		//根据配置的存储方式，分别存储历史记录，1 为 存储在用户个性化设置中， 否则存储在本地 localStorage中
		if(this.config.storage == "1"){
			historyList.historyKey = key;
			Ccay.Personalized.save(historyList, false);
		}else{
			var storageData = {history: historyList, creationDate : new Date().getTime()}
			Ccay.LocalStorage.setItem(key, JSON.stringify(storageData));
		}
	},
	/**根据配置获取历史选择记录（个性化与localStorage）
	 * @param key     key
	 * @param isSort  是否进行排序，默认会进行排序
	 * */
	getHistory : function(key, unSort){
		if(!key){
			return [];
		}
		//获取配置的保存方式，根据保存方式去获取历史记录， 
		var historyList;
		if(this.config.storage == "1"){
			historyList = Ccay.Personalized._settings.get(key) || [];
		}else{
			var storageData = Ccay.LocalStorage.getItem(key)
			historyList = storageData  && Ccay.DataHelper.toJson(storageData).history || [];
		}
		while(historyList && historyList.length > this.config.length){
			historyList.pop();
		}
		//通过得到排序方式，对历史记录进行排序, sortType 为 1 则根据时间排序，否则根据使用的次数进行排序。
		if(!unSort){
			Ccay.DataHelper.sort("time", "desc", historyList );
		}
		/*
		 * 修复下拉框历史记录的times次数时不起效果，在此添加个判断。
		 * */
		if(this.config.sort == "0"){   
			Ccay.DataHelper.sort("times", "desc", historyList );
		 }
		return historyList;
	},
	/** 删除历史选择记录（）*/
	delInvalidHistory : function(key,value){
		if(!key){
			return;
		}
		var history = this.getHistory(key);
		if(Ccay.DataHelper.hasValue(value)){
			$.each(history,function(i,item){
				if(item.value == value){
					history.splice(i,1);
					return false;
				}
			})
		}
		if(this.config.storage == "1"){
			history.historyKey = key;
			Ccay.Personalized.save(history, false);
		}else{
			var storageData = {history: history, creationDate : new Date().getTime()}
			Ccay.LocalStorage.setItem(key, JSON.stringify(storageData));
		}
	},
	    
	hasHistory : function(op){
		var his = this.getHistory(op.historyKey || ( op.ajax && op.ajax.url ));
		return his.length > 0 ? true : false;
	},
	//判断是否支持历史选项记录功能
	isSupport : function(op){
		return op.historySupport || this.config.enable && op.historySupport !== false;
		
	}

}
Ccay.History.init();